package com.zxl.yjb.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.zxl.yjb.R;
import com.zxl.yjb.activity.home.order.OrderDetailActivity;
import com.zxl.yjb.activity.home.order.SosDetailActivity;
import com.zxl.yjb.activity.home.sharemessage.MessageListActivity;
import com.zxl.yjb.activity.im.DialogActivity;
import com.zxl.yjb.activity.my.MyWalletActivity;
import com.zxl.yjb.activity.my.RealNameAuthenticationActivity;
import com.zxl.yjb.activity.nearby.NearbyActivity;
import com.zxl.yjb.adapter.BottomNavAdapter;
import com.zxl.yjb.app.Const;
import com.zxl.yjb.app.update.UpdateManager;
import com.zxl.yjb.base.BaseActivity;
import com.zxl.yjb.bean.LoginSucessBean;
import com.zxl.yjb.bean.MessageEvent;
import com.zxl.yjb.bean.OrderTakeBean;
import com.zxl.yjb.bean.SOSHaveReadBean;
import com.zxl.yjb.fragment.home.HomeFragment;
import com.zxl.yjb.fragment.my.MyFragment;
import com.zxl.yjb.fragment.near.NearbyFragment;
import com.zxl.yjb.http.HostUrl;
import com.zxl.yjb.http.manager.DataManager;
import com.zxl.yjb.http.observer.ObserverOnNextListener;
import com.zxl.yjb.http.observer.ProgressObserver;
import com.zxl.yjb.runtimepermissions.PermissionsManager;
import com.zxl.yjb.runtimepermissions.PermissionsResultAction;
import com.zxl.yjb.utils.DisplayUtil;
import com.zxl.yjb.utils.SPUtil;
import com.zxl.yjb.utils.SaveBeanUtil;
import com.zxl.yjb.widget.NoScrollViewPager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.UserInfo;

import static com.zxl.yjb.app.Const.SEALTALK_LOGIN_ID;

public class MainActivity extends BaseActivity {


    @BindView(R.id.vp_home)
    NoScrollViewPager vp_home;
    @BindView(R.id.tb_bottom_nav_home)
    TabLayout tb_bottom_nav_home;
    @BindView(R.id.container)
    LinearLayout container;

    private BottomNavAdapter bottomNavAdapter;
    private List<Fragment> fragmentList;
    private int[] bottom_nav_ress_def = {R.mipmap.home_off, R.mipmap.fjqz_a, R.mipmap.wd_a};
    private int[] bottom_nav_ress_sel = {R.mipmap.home_on, R.mipmap.fjqz_b, R.mipmap.wd_b};
    private String[] bottomNavName = {"主页", "附近求助", "我的"};
    private TextView[] tv_bottom_navs = new TextView[3];       //导航栏中textView
    private ImageView[] iv_bottom_navs = new ImageView[3];     //导航栏中ImageView
    private HomeFragment homeFragment;
    private NearbyFragment nearbyFragment;
    private MyFragment myFragment;
    private LoginSucessBean loginSucessBean;

    private View sosRedPoint;

    private boolean isDialogShow = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        Object bean = SaveBeanUtil.getBean(this, Const.VIPINFO);
        if (bean != null) {
            loginSucessBean = (LoginSucessBean) bean;
        }
        String idstatus = getIntent().getStringExtra("idstatus");
        if (!TextUtils.isEmpty(idstatus) && idstatus.equals("0")) {
            DisplayUtil.diaplayDialog(MainActivity.this, "您还没有实名认证", "","稍后","去认证",null, new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this,RealNameAuthenticationActivity.class));
                }
            });
        }
        EventBus.getDefault().register(this);
        JPushInterface.setAlias(this, Const.JGTS_SEQUENCE, loginSucessBean.getUid() + "");
        requestPermissions();
        UpdateManager.getUpdateManager().checkAppUpdate(this, false, 0);
        initView();
        initFragment();
        addAdapter();
        sosHaveNoRead();
        refreshUserInfo(); //这个接口没有返回ryToken,以后打开

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            String stringExtra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            OnPushMsg(stringExtra);
        }

    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            String stringExtra = bundle.getString(JPushInterface.EXTRA_EXTRA);
            OnPushMsg(stringExtra);
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (isDialogShow) {
            getUnoptOrderList();
        }

        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_PROVINCE,"");
        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_CITY,"");
        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_DISTRICT,"");
        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_STREET,"");

    }

    @Override
    protected void initView() {
        container = findViewById(R.id.container);
    }


    private void initFragment() {
        fragmentList = new ArrayList<>();
        homeFragment = new HomeFragment();
        myFragment = new MyFragment();
        nearbyFragment = new NearbyFragment();
        fragmentList.add(homeFragment);
        fragmentList.add(nearbyFragment);
        fragmentList.add(myFragment);
    }


    private void addAdapter() {
        bottomNavAdapter = new BottomNavAdapter(getSupportFragmentManager(), fragmentList, bottomNavName);
        vp_home.setAdapter(bottomNavAdapter);
        vp_home.setOffscreenPageLimit(2);
//        tb_bottom_nav_home.setupWithViewPager(vp_home);

        for (int i = 0; i < bottomNavName.length; i++) {
            TabLayout.Tab mTab = tb_bottom_nav_home.newTab();
            RelativeLayout ll_bottom_nav = (RelativeLayout) getLayoutInflater().inflate(R.layout.bottom_nav_view, null, false);
            TextView tv_bottom_nav = (TextView) ll_bottom_nav.findViewById(R.id.tv_bottom_nav);
            ImageView iv_bottom_nav = (ImageView) ll_bottom_nav.findViewById(R.id.iv_bottom_nav);
            if (i == 0) {
                tv_bottom_nav.setTextColor(getResources().getColor(R.color.red_color));
                iv_bottom_nav.setImageResource(bottom_nav_ress_sel[i]);
            } else {
                iv_bottom_nav.setImageResource(bottom_nav_ress_def[i]);
            }

            if (i == 1) {
                sosRedPoint = ll_bottom_nav.findViewById(R.id.iv_red);
            }
            tv_bottom_nav.setText(bottomNavName[i]);
            tv_bottom_navs[i] = tv_bottom_nav;
            iv_bottom_navs[i] = iv_bottom_nav;
            mTab.setCustomView(ll_bottom_nav);//为导航栏设置自定义View
            tb_bottom_nav_home.addTab(mTab, i);
        }

        tb_bottom_nav_home.getTabAt(1).getCustomView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sosRedPoint.setVisibility(View.GONE);
                startActivity(new Intent(getApplicationContext(), NearbyActivity.class));// 切换到指定页面
            }
        });

        tb_bottom_nav_home.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                if (tab == tb_bottom_nav_home.getTabAt(0)) {
                    iv_bottom_navs[0].setImageResource(bottom_nav_ress_sel[0]);//导航栏图片
                    tv_bottom_navs[0].setTextColor(getResources().getColor(R.color.red_color));  //导航栏字体颜色
                    vp_home.setCurrentItem(0, false);// 切换到指定页面
                } else if (tab == tb_bottom_nav_home.getTabAt(1)) {

                } else if (tab == tb_bottom_nav_home.getTabAt(2)) {
                    iv_bottom_navs[2].setImageResource(bottom_nav_ress_sel[2]);
                    tv_bottom_navs[2].setTextColor(getResources().getColor(R.color.red_color));
                    vp_home.setCurrentItem(2, false);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                if (tab == tb_bottom_nav_home.getTabAt(0)) {
                    iv_bottom_navs[0].setImageResource(bottom_nav_ress_def[0]);
                    tv_bottom_navs[0].setTextColor(getResources().getColor(R.color.black_color));
                } else if (tab == tb_bottom_nav_home.getTabAt(1)) {

                } else if (tab == tb_bottom_nav_home.getTabAt(2)) {
                    iv_bottom_navs[2].setImageResource(bottom_nav_ress_def[2]);
                    tv_bottom_navs[2].setTextColor(getResources().getColor(R.color.black_color));
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }


    private void requestPermissions() {
        PermissionsManager.getInstance().requestAllManifestPermissionsIfNecessary(this, new PermissionsResultAction() {
            @Override
            public void onGranted() {
//				Toast.makeText(MainActivity.this, "All permissions have been granted", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onDenied(String permission) {
                //Toast.makeText(MainActivity.this, "Permission " + permission + " has been denied", Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        PermissionsManager.getInstance().notifyPermissionsChange(permissions, grantResults);
    }


    /**
     * 获取个人信息
     */
    private void refreshUserInfo() {
        DataManager dataManager = new DataManager();
        dataManager.getUserInfo(new ProgressObserver<LoginSucessBean>(new ObserverOnNextListener<LoginSucessBean>() {
            @Override
            public void onNext(LoginSucessBean loginSucessBean) {
                if (loginSucessBean == null)
                    return;
                MainActivity.this.loginSucessBean = loginSucessBean;
                SaveBeanUtil.putBean(getApplicationContext(), Const.VIPINFO, loginSucessBean);
                upDataImInfo(loginSucessBean.getNickname(), HostUrl.HOSTPIC + loginSucessBean.getFace_img());
                myFragment.refrensh();//刷新我的页面
            }
        }, this), loginSucessBean.getUid() + "");
    }


    /*获取未操作的订单*/
    private void getUnoptOrderList() {
        DataManager dataManager = new DataManager();
        dataManager.order_accept1refuse2_page_state(new ProgressObserver<ArrayList<OrderTakeBean>>(new ObserverOnNextListener<ArrayList<OrderTakeBean>>() {
            @Override
            public void onNext(ArrayList<OrderTakeBean> orderTakeBeans) {
                if (orderTakeBeans.size() > 0) {
                    Intent intent = new Intent(MainActivity.this, DialogActivity.class);
                    intent.putExtra("id", orderTakeBeans.get(0).getOrder_sn());
                    intent.putExtra("charge_id", orderTakeBeans.get(0).getCharge_id());
                    intent.putExtra("amount", orderTakeBeans.get(0).getAmount());
                    startActivity(intent);
                }

            }
        }, this), new HashMap<String, String>());
    }

    /*sos是否未读*/
    private void sosHaveNoRead() {
        DataManager dataManager = new DataManager();
        dataManager.sosHaveNoRead(new ProgressObserver<SOSHaveReadBean>(new ObserverOnNextListener<SOSHaveReadBean>() {
            @Override
            public void onNext(SOSHaveReadBean sosHaveReadBean) {
                if ("1".equals(sosHaveReadBean.getHaveNoRead_yes1_no0())) {
                    sosRedPoint.setVisibility(View.VISIBLE);
                } else {
                    sosRedPoint.setVisibility(View.GONE);
                }
            }
        }, this), new HashMap<String, String>());

    }


    //修改im当前用户信息
    private void upDataImInfo(String nickName, String facePath) {
        //执行一次就可以
        String id = (String) SPUtil.get(getApplication(), SEALTALK_LOGIN_ID, "");
        if (TextUtils.isEmpty(id)) {
            return;
        }
        RongIM.getInstance().setCurrentUserInfo(new UserInfo(id, nickName, Uri.parse(facePath)));
    }

    /**
     * 从推送中打开Mainactivity
     *
     * @param stringExtra
     */
    private void OnPushMsg(String stringExtra) {
        if (TextUtils.isEmpty(stringExtra)) {
            return;
        }
        String order_sn = "";
        String request_id = "";
        String id_new_sos = "";
        String type = "";
        try {
            JSONObject jsonObject = new JSONObject(stringExtra);
            order_sn = jsonObject.optString("order_sn");
            request_id = jsonObject.optString("request_id");
            id_new_sos = jsonObject.optString("id_new_sos");
            type = jsonObject.optString("type");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (Const.JPUSH_SOS_TYPE.equals(type)) {
            Intent intent = new Intent(MainActivity.this, SosDetailActivity.class);
            intent.putExtra("id", id_new_sos);
            startActivity(intent);
        } else if (Const.JPUSH_MSG_TYPE.equals(type) | "1".equals(type)) {
            Intent intent = new Intent(MainActivity.this, OrderDetailActivity.class);
            intent.putExtra("id", order_sn);
            intent.putExtra("user_id", request_id)
                    .putExtra("from", "take_list");
            startActivity(intent);
        } else if ("3".equals(type)) {
            Intent intent = new Intent(MainActivity.this, MyWalletActivity.class);
            startActivity(intent);
        }


//        Intent intent = new Intent(getApplicationContext(), OrderTakeActivity.class);
//        startActivity(intent);
        /*Intent intent = new Intent(getApplicationContext(), DialogActivity.class);
//                    intent.putExtra(Const.KEY_EXTRAS, stringExtra);
        intent.putExtra("id", stringExtra);
        intent.putExtra("charge_id", getIntent().getStringExtra("charge_id"));
        intent.putExtra("amount",  getIntent().getStringExtra("amount"));
        startActivity(intent);*/
      /*  if (!TextUtils.isEmpty(stringExtra)){
            Gson gson = new Gson();
            JpushExtraBean extraBean = gson.fromJson(stringExtra, JpushExtraBean.class);
            switch (extraBean.getType()) {
                case Const.JPUSH_MSG_TYPE://对方已支付，确认接单
                    Intent intent = new Intent(getApplicationContext(), DialogActivity.class);
                    intent.putExtra(Const.KEY_EXTRAS, stringExtra);
                    startActivity(intent);
                    break;
            }
        }*/
    }


    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(MessageEvent messageEvent) {
        if ("refreshUserInfo".equals(messageEvent.getMessage())) {
            refreshUserInfo();
        } else if ("notshow".equals(messageEvent.getMessage())) {
            isDialogShow = false;
        } else if ("downloadProgress".equals(messageEvent.getMessage())) {
            UpdateManager.getUpdateManager().updateDownloadProgress((int) messageEvent.getObject());
        } else if ("new_sos".equals(messageEvent.getMessage())) {
            if (sosRedPoint != null)
                sosRedPoint.setVisibility(View.VISIBLE);
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_PROVINCE,"");
        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_CITY,"");
        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_DISTRICT,"");
        SaveBeanUtil.putBean(MainActivity.this, Const.LOCATION_SELECT_STREET,"");
    }

}
